/**
 * 游戏主界面
 */

class GameScene extends eui.Component {
    private myOption: any = {}; //自定义属性对象
    private gameHeader: eui.Component;  //游戏头部
    private gameFooter: any;    //游戏底部
    private balloons: Array<any> = [];  //正在运动的气球集合
    private balloonsPool: Array<any> = []; //气球对象池
    private touchX: number;     //触摸第一点的X
    private touchY: number;     //触摸第一点的Y
    private myMask: any;
    private BALLOON_COLOR_LIST: Array<any> = [{
        color:'red',
        colorValue:0xED7073
    },{
        color:'blue',
        colorValue:0x3D9AD7
    },{
        color:'yellow',
        colorValue:0xF6B752
    },{
        color:'green',
        colorValue:0x89F088
    },{
        color:'pink',
        colorValue:0xCA94E5
    }]; //不同的气球以及对应的颜色
    private GAMEFOOTER_Y: number; //底部的Y坐标
    private frame: number = 0; //游戏总帧数
    private CURRENT_LEVEL_COLOR: any;
    private CURRENT_RIGHT_BALLOONS: number = 0;
    private CURRENT_NEET_RIGHT: number;
    private CURRENT_HEART_NUM: number;
    private CURRENT_LEVEL: number;//当前关卡
    private CURRENT_BALLOON_SPEED: number;
    private CURRENT_LEVEL_COUNTDOWN: number;
    private CURRENT_SCORE: number;  //当前的分数
    private COUNTDOWN_THREAD;
    private COUNTDOWN_FORHEART_THREAD;
    private SHOWPOP_THREAD;
    private REGETHEART = 0;
    private failDialog;
    private BOOM_PANEL: eui.Group;
    private BALLOONS_PANEL: eui.Group;
    private CURRENT_LOSE_TIME: number;
    private BOOM_SOUND;
    private SUCCESS_SOUND;
    private FAIL_SOUND;
    private POP_BG;
    private invitedList;
    private FETCH_THREAD;
    private HISTORY_SCORE = 0;
    private CAN_PUSH_SCORE = false;
    private FIRST_BALLOONS;
    private GAME_TIME = 0;
    private GAME_TIME_THREAD;

    private MORE_HEART_CACHE; // 更多心的模型对象

    public constructor(stageHeight,stageWidth) {
        super();
        //由于当前的对象无法获取到舞台的高度和宽度所以从根组件传递进来
        this.myOption.stageHeight = stageHeight;
        this.myOption.stageWidth = stageWidth;
        this.GAMEFOOTER_Y = this.myOption.stageHeight - 300;

        this.BOOM_SOUND  = wx.createInnerAudioContext();
        //sound 加载完成监听
        this.BOOM_SOUND.src = "audio/boom.mp3";

        this.SUCCESS_SOUND  = wx.createInnerAudioContext();
        //sound 加载完成监听
        this.SUCCESS_SOUND.src = "audio/success.mp3";

        this.FAIL_SOUND  = wx.createInnerAudioContext();
        //sound 加载完成监听
        this.FAIL_SOUND.src = "audio/fail.mp3";
        // this.reset()
    }

    private async getHistoryScore() {
        try {
            let result: any = await platform.request({
                url:platform.globalPath + '/score/highest',
                method: 'GET',
                data: {userId: wx.getStorageSync('userId')}
            })
            if(result.data.success) {
                this.HISTORY_SCORE = result.data.data;
                this.CAN_PUSH_SCORE = true;
            }
        } catch (error) {
            
        }
    }

    /**
     * 游戏变量重置
     */
    public reset() {
        this.GAME_TIME = 0;
        this.CURRENT_HEART_NUM = 5; //设置心数
        this.CURRENT_LEVEL = 1;
        this.CURRENT_SCORE = 0;
        this.CURRENT_LOSE_TIME = 0;
        this.init();   
        this.invitedList = [];
        this.HISTORY_SCORE = 0 ;
        this.CAN_PUSH_SCORE =false;
        this.getHistoryScore();
    }

    /**
     * 游戏初始化
     */
    public init() {
        this.countTime();
        this.initData();
        this.initMask()
        this.initBaseScene();
        this.initLevelScene();
        this.initFirstBalloons();
        this.showCurrentLevel();
        this.showPop();
        // this.showFailResult()
    }

    private countTime() {
        this.GAME_TIME_THREAD = setInterval(() => {
            this.GAME_TIME ++;
        }, 1000)
    }

    private initFirstBalloons() {
        if(this.CURRENT_LEVEL <= 5) {
            this.FIRST_BALLOONS = [this.CURRENT_LEVEL_COLOR.color];
        }else if(this.CURRENT_LEVEL > 5 && this.CURRENT_LEVEL <= 15) {
            this.FIRST_BALLOONS = [this.CURRENT_LEVEL_COLOR.color];
        }else if(this.CURRENT_LEVEL > 15 && this.CURRENT_LEVEL <= 25) {
            this.FIRST_BALLOONS = [this.CURRENT_LEVEL_COLOR.color,this.CURRENT_LEVEL_COLOR.color,this.CURRENT_LEVEL_COLOR.color];
        }else {
           this.FIRST_BALLOONS = [this.CURRENT_LEVEL_COLOR.color,this.CURRENT_LEVEL_COLOR.color,this.CURRENT_LEVEL_COLOR.color];
        }
        if(this.FIRST_BALLOONS.length < 5){
            this.FIRST_BALLOONS.push(this.getRandomColor().color);
        }
        this.FIRST_BALLOONS.sort((a,b) => {
            return Math.random() > 0.5
        });
    }

    private async fetchInvitedList() {
        try {
            let result: any = await platform.request({
                url:platform.globalPath + '/sharecode/queryverifylist',
                method: 'GET',
                data: {userId: wx.getStorageSync('userId')}
            })
            if(result.data.success) this.invitedList = result.data.data;
        } catch (error) {
            
        }

        this.FETCH_THREAD = setTimeout(() => {
            this.fetchInvitedList();
        },16000)
    }

    private showPop() {
        this.fetchInvitedList();
        this.SHOWPOP_THREAD = setInterval(async () => {
            if(this.invitedList.length > 0) {
                let code = this.invitedList.shift().id;
                try {
                    let result: any = await platform.request({
                        url:platform.globalPath + '/sharecode/addstar',
                        method: 'POST',
                        data: {id: code}
                    })
                    if(result.data.success) {
                        this.addHeart();
                        if(!this.POP_BG){
                            this.POP_BG = new eui.Component();
                            this.POP_BG.skinName = 'invite';
                        }
                        this.POP_BG.getChildByName('inviteName').text = `好友${result.data.data}已帮你助力，获得1颗小心心`
                        this.POP_BG.y = -this.POP_BG.height;
                        this.POP_BG.alpha = 0;
                        this.gameHeader.addChild(this.POP_BG)
                        egret.Tween
                            .get(this.POP_BG, {
                                loop: false,//设置循环播放
                                onChangeObj: this//更新函数作用域
                            })
                            .to({alpha: 1,y: 80}, 500)
                            .wait(1500)
                            .to({alpha: 0,y: -this.POP_BG.height}, 500)//设置2000毫秒内 rotation 属性变为360
                    }    
                } catch (error) {
                    
                }
            }
        },5000)
    }
    /**
     * 初始化缓存数据
     */
    private initData() {
        let {levelTargetBalloonNum, levelBalloonSpeed, countDownTime} = this.getLevelBaseData();
        this.balloons = [];
        this.balloonsPool = [];
        this.frame = 0;
        this.CURRENT_NEET_RIGHT = levelTargetBalloonNum;
        this.CURRENT_BALLOON_SPEED = levelBalloonSpeed;
        this.CURRENT_LEVEL_COUNTDOWN = countDownTime;
        this.MORE_HEART_CACHE = null;
    }

    /**
     * 搭建游戏基础内容
     */
    private initBaseScene() {
        //创建一个存储爆炸结果的画布
        this.BOOM_PANEL = new eui.Group();
        this.BOOM_PANEL.width = this.myOption.stageWidth;
        this.BOOM_PANEL.height = this.myOption.stageHeight;

        this.addChild(this.BOOM_PANEL)

        //创建一个存储气球的画布
        this.BALLOONS_PANEL = new eui.Group();
        this.BALLOONS_PANEL.width = this.myOption.stageWidth;
        this.BALLOONS_PANEL.height = this.myOption.stageHeight;

        this.addChild(this.BALLOONS_PANEL)

        //创建头部资源
        this.gameHeader = new eui.Component();
        this.gameHeader.skinName = 'gameHeader';
        this.addChild(this.gameHeader);

        //添加当前分数
        let score: any = this.gameHeader.getChildByName('score');
        score.text = this.CURRENT_SCORE;

        //创建底部资源
        this.gameFooter = new eui.Component();
        this.gameFooter.skinName = 'gameFooter';
        this.gameFooter.y = this.GAMEFOOTER_Y;
        this.addChild(this.gameFooter);

    }

    /**
     * 创建关卡等级基础内容
     */
    private initLevelScene(level?) {
        
        this.initHeart();

        this.initGoal();
    }

    /**
     * 初始化星星数量
     */
    private initHeart() {
        let heartWrapper: any = this.gameHeader.getChildByName('heartWrapper');
        let showHeartNum;
        if(this.CURRENT_HEART_NUM > 5) {
            showHeartNum = 5;
        }else {
            showHeartNum = this.CURRENT_HEART_NUM;
        }
        for(let i = 0;i < showHeartNum; i++) {
            let heart = this.createBitmapByName("heart2_png");
            heart.x = i * 70;
            heart.y = 25;
            heartWrapper.addChild(heart)
        }
        this.renderMoreHeart();
    }

    private renderMoreHeart() {
        let mortHeartNum = this.CURRENT_HEART_NUM  - 5;
        this.MORE_HEART_CACHE = this.MORE_HEART_CACHE || this.gameHeader.getChildByName('moreHeart');
        if(mortHeartNum > 0) {
            //展示额外的心
            if(this.gameHeader.getChildIndex(this.MORE_HEART_CACHE) < 0){
                this.gameHeader.addChild(this.MORE_HEART_CACHE);
            }
            this.MORE_HEART_CACHE.getChildByName('moreHeartNum').text = mortHeartNum + '+';
        }else{
            if(this.gameHeader.getChildIndex(this.MORE_HEART_CACHE) > 0) this.gameHeader.removeChild(this.MORE_HEART_CACHE);
        }
    }

    private reduceHeart() {
        this.CURRENT_HEART_NUM --;
        if(this.CURRENT_HEART_NUM >= 5){
            this.renderMoreHeart();
        }else {
            let heartWrapper: any = this.gameHeader.getChildByName('heartWrapper');
            heartWrapper.removeChildAt(heartWrapper.numChildren - 1)
        }
    }

    private addHeart() {
        if(this.CURRENT_HEART_NUM >= 5){
            this.CURRENT_HEART_NUM ++;
            this.renderMoreHeart();
        }else {
            this.CURRENT_HEART_NUM ++;
            let heartWrapper: any = this.gameHeader.getChildByName('heartWrapper');
            let existHearts = heartWrapper.numChildren - 5;
            let heart = this.createBitmapByName("heart2_png");
            heart.x = existHearts * 70;
            heart.y = 25;
            heartWrapper.addChild(heart)
        }
    }

    /**
     * 初始化倒计时时间
     */
    private initCountDown() {
        //获取当权关卡的时间
        let countDown: any = this.gameHeader.getChildByName('countDown');
        countDown.text = this.CURRENT_LEVEL_COUNTDOWN;

        if(this.COUNTDOWN_THREAD) clearInterval(this.COUNTDOWN_THREAD);
        this.COUNTDOWN_THREAD = setInterval(() => {
            if(parseInt(countDown.text) === 0) {
                 //删除一颗心并重新倒计时
                 this.reduceHeart();
                 if(this.CURRENT_HEART_NUM === 0) {
                     //游戏结束
                     this.checkGameIsOver();
                 }else{
                     return this.initCountDown();
                 }
            }else {
                countDown.text = parseInt(countDown.text) - 1;
            }
        }, 1000)
    }

    /**
     * 初始化目标数量以及颜色
     */
    private initGoal() {
        this.CURRENT_LEVEL_COLOR = this.getRandomColor();
        let goalBalloon = this.gameFooter.getChildByName('goalBalloon');
        goalBalloon.texture = RES.getRes(`${this.CURRENT_LEVEL_COLOR.color}_balloon_small_png`);
        
        this.CURRENT_RIGHT_BALLOONS = 0;
        this.updateCurrentNum()

        let targetNum = this.gameFooter.getChildByName('targetNum');
        targetNum.text = `/${this.CURRENT_NEET_RIGHT}`;
    }

    /**
     * 展示前端关卡
     */
    private showCurrentLevel() {
        this.addChild(this.myMask)
        let isVisited = wx.getStorageSync('isVisited');
        if(isVisited) {
            let levelDialog = new eui.Component();
            levelDialog.skinName = 'level';
            levelDialog.y = this.myOption.stageHeight / 2 - levelDialog.height / 2;
            let label: any = levelDialog.getChildByName('level');
            label.text = `第 ${this.CURRENT_LEVEL} 关`
            this.addChild(levelDialog);
            setTimeout(() => {
                this.removeChild(levelDialog);
                this.removeChild(this.myMask);
                this.addEventListener(egret.Event.ENTER_FRAME, this.loop, this);
                this.initCountDown();
            }, 1000)
        }else {
            let newImage = this.createBitmapByName(`new_png`);
            newImage.name = "newImage"
            this.addChild(newImage)
            newImage.y = -188 + this.GAMEFOOTER_Y;
            newImage.x = 36;
            this.addEventListener(egret.TouchEvent.TOUCH_TAP, this.newVisited, this);
        }
    }
    
    private newVisited() {
        this.removeChild(this.getChildByName('newImage'));
        wx.setStorageSync('isVisited',true)
        this.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.newVisited, this);
        let levelDialog = new eui.Component();
        levelDialog.skinName = 'level';
        levelDialog.y = this.myOption.stageHeight / 2 - levelDialog.height / 2;
        let label: any = levelDialog.getChildByName('level');
        label.text = `第 ${this.CURRENT_LEVEL} 关`
        this.addChild(levelDialog);
        setTimeout(() => {
            this.removeChild(levelDialog);
            this.removeChild(this.myMask);
            this.addEventListener(egret.Event.ENTER_FRAME, this.loop, this);
            this.initCountDown();
        }, 1000)
    }

    private updateCurrentNum() {
        let currentNum = this.gameFooter.getChildByName('currentNum');
        currentNum.text = this.CURRENT_RIGHT_BALLOONS;
        currentNum.textColor = this.CURRENT_LEVEL_COLOR.colorValue;
        if(this.CURRENT_RIGHT_BALLOONS >= 10) {
            currentNum.x = 70.5;
        }else {
            currentNum.x = 87.5;
        }
    }

    private createBitmapByName(name: string): eui.Image {
        let result = new eui.Image();
        let texture: egret.Texture = RES.getRes(name);
        result.texture = texture;
        return result;
    }

    private createBalloons() {
        let balloon = this.getBalloon();
        this.BALLOONS_PANEL.addChild(balloon)
        this.balloons.push(balloon);
    }

    private getBalloon(): eui.Image {
        let color;
        if(this.FIRST_BALLOONS.length > 0){
            color = this.FIRST_BALLOONS.pop()
        }else {
            let randomArr = [this.getRandomColor().color,this.getRandomColor().color,this.CURRENT_LEVEL_COLOR.color];
            color = randomArr[Math.floor(Math.random()*3)]
        }
        let newBalloon;
        if(this.balloonsPool.length > 0) {
            newBalloon = this.balloonsPool.shift()
            newBalloon.texture = RES.getRes(`${color}_balloon_png`);
        }else {
            newBalloon = this.createBitmapByName(`${color}_balloon_png`);
            newBalloon.addEventListener(egret.TouchEvent.TOUCH_TAP, () => {
                if(!newBalloon.visible) return;
                if(platform.music) {
                    this.BOOM_SOUND.seek(0)
                    this.BOOM_SOUND.play();
                }
                newBalloon.visible = false;
                this.createBoomAnimation(newBalloon.x + 45 ,newBalloon.y + 60, newBalloon.balloonColor)
                this.checkPlayResult(newBalloon.balloonColor);
            }, this);
        }
        newBalloon.visible = true;
        newBalloon.x = this.rnd(0, this.myOption.stageWidth - newBalloon.width);
        newBalloon.y = this.myOption.stageHeight;
        newBalloon.balloonColor = color;
        return newBalloon;
    }

    private loop() {
        this.frame ++;
        //每隔60帧创建一个气球对象
        if(this.frame % 60 === 0){
            this.createBalloons()
        }
        
        this.balloons = this.balloons.filter((balloon) => {
            if( (balloon.y < (-balloon.height)) || !balloon.visible) {
                this.balloonsPool.push(balloon)
                this.BALLOONS_PANEL.removeChild(balloon)
                return false;
            }else{
                balloon.y -= this.CURRENT_BALLOON_SPEED;
                return true;
            }
        })

    }

    /**
     * 判断当前击破是否有效
     */
    private checkPlayResult(balloonColor) {
        if(this.CURRENT_LEVEL_COLOR.color === balloonColor){
            //击中了有效气球
            this.CURRENT_RIGHT_BALLOONS += 1;
            this.updateCurrentNum()
        }else {
            this.reduceHeart();
        }
        this.checkGameIsOver();
    }

    /**
     * 判断当前游戏是否结束（胜利或者/失败）
     */
    private checkGameIsOver() {
        if(this.CURRENT_NEET_RIGHT === this.CURRENT_RIGHT_BALLOONS){
            //晋级
            this.releaseAllEvent();
            this.removeChild(this.BALLOONS_PANEL)
            setTimeout(() => {
                if(platform.music) this.SUCCESS_SOUND.play();
                this.showSuccessResult();
            }, 1000)
        } else if(this.CURRENT_HEART_NUM === 0) {
            //失败
            if(platform.music) this.FAIL_SOUND.play();
            this.releaseAllEvent();
            this.showFailResult();
        }else {
            return 
        }
    }

    /**
     * 展示晋级界面
     */
    private async showSuccessResult() {
        this.addChild(this.myMask)
        let successDialog = new eui.Component();
        successDialog.skinName = 'success';
        successDialog.y = this.myOption.stageHeight / 2 - successDialog.height / 2;
        this.addChild(successDialog);
        this.CURRENT_SCORE = this.CURRENT_LEVEL % 3 === 0 ? this.CURRENT_SCORE + 4 : this.CURRENT_SCORE + 1;
        this.CURRENT_LEVEL ++;
        // this.CURRENT_HEART_NUM ++;
        setTimeout(() => {
            this.removeChild(successDialog)
            this.removeChild(this.myMask)
            this.removeChildren();
            this.init();
        }, 2000)
    }

    private releaseAllEvent() {
        clearInterval(this.FETCH_THREAD);
        clearInterval(this.SHOWPOP_THREAD);
        this.removeEventListener(egret.Event.ENTER_FRAME, this.loop, this);
        clearInterval(this.COUNTDOWN_THREAD);
    }

    /**
     * 展示失败页面
     */
    private showFailResult() {
        this.addChild(this.myMask)
        this.failDialog = new eui.Component();
        this.failDialog.skinName = 'fail';
        this.failDialog.y = this.myOption.stageHeight / 2 - this.failDialog.height / 2 - 53;
        let countDown:any = this.failDialog.getChildByName('countDown');
        this.addChild(this.failDialog);
        this.countDownForHeart(this.failDialog);
        let leftLabel:any = this.failDialog.getChildByName('leftLabel');
        let shareBtn: any = this.failDialog.getChildByName('shareBtn');
        //leftLabel添加监听
        leftLabel.addEventListener(egret.TouchEvent.TOUCH_TAP, this.leftLabelBtn, this);
        shareBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.shareApp, this);
    }

    private shareApp() {
        try { 
            platform.request({
                url:platform.globalPath + '/button/record',
                method: 'POST',
                data: {userId: wx.getStorageSync('userId'),buttonType: 3}
            })
        } catch (error) {
            
        }
        let shareDialog = new eui.Component();
        this.failDialog.visible = false;
        shareDialog.y = this.myOption.stageHeight / 2 - shareDialog.height / 2 - 100;
        shareDialog.skinName = 'shareDialog';
        this.addChild(shareDialog);
        let sureBtn:any = shareDialog.getChildByName('sure');
        wx.shareAppMessage({
            title:'孩子从数学0基础秒杀大学生 就靠它了',
            imageUrl: platform.globalPath + '/assets/img/share.jpg',
            query:`take=${wx.getStorageSync('take')}`
        })

        sureBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, () => {
            this.removeChild(shareDialog);
            this.failDialog.visible = true;
        }, this);

    }

    private leftLabelBtn() {
        let leftLabel:any = this.failDialog.getChildByName('leftLabel');
        let shareBtn: any = this.failDialog.getChildByName('shareBtn');
        let currentValue = leftLabel.text;
        //清除事件
        leftLabel.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.leftLabelBtn, this);
        shareBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.shareApp, this);
        clearInterval(this.COUNTDOWN_FORHEART_THREAD)
        // //清除当前弹窗加载的内容
        this.removeChild(this.failDialog)

        //显示分数
        this.showScorePage();
    }

    private async showScorePage(){
        clearInterval(this.GAME_TIME_THREAD)
        //上传成绩到服务器
        try {
            if(this.CAN_PUSH_SCORE && this.CURRENT_SCORE > this.HISTORY_SCORE) {
                let result = await platform.request({
                    url:platform.globalPath + '/score/record',
                    method: 'POST',
                    data: {userId: wx.getStorageSync('userId'), score: this.CURRENT_SCORE, spendTime: this.GAME_TIME}
                })

                if(result.data.success) {
                        let gameScoreData = {
                            wxgame: {
                                score: this.CURRENT_SCORE,
                                update_time: new Date().getTime(),
                            },
                        }

                        let userKVData = {
                            key: "score",
                            value: JSON.stringify(gameScoreData),
                        }

                        wx.setUserCloudStorage({
                            KVDataList: [userKVData],
                            success: function (res) {
                                console.log('--success res:', res);
                            },
                            fail: function (res) {
                                console.log('--fail res:', res);
                            },
                            complete: function (res) {
                                console.log('--complete res:', res);
                            },
                        });
                }
            }

        } catch (error) {
            
        }

        let scorePage: any = new eui.Component();
        scorePage.skinName = 'scorePage';
        scorePage.y = this.myOption.stageHeight / 2 - scorePage.height / 2 - 100;
        this.addChild(scorePage);

        scorePage.getChildByName('score').text = this.CURRENT_SCORE;
        scorePage.getChildByName('goHome').addEventListener(egret.TouchEvent.TOUCH_TAP, () => {
             this.release();
             SceneMange.getInstance().changeScene('beginScene');
        }, this);
    }

    private countDownForHeart(failDialog) {
        let countDown: any = failDialog.getChildByName('countDown');
        let leftLabel = failDialog.getChildByName('leftLabel');
        let second = 0;
        let min = this.CURRENT_LOSE_TIME * 1 + 1;
        let getHeart = this.CURRENT_LOSE_TIME * 1 + 1;

        let showStr =('0'+min).substr(-2) + ':' + ('0'+second).substr(-2);
        countDown.text = showStr;
        if(this.COUNTDOWN_FORHEART_THREAD) clearInterval(this.COUNTDOWN_FORHEART_THREAD);
        this.COUNTDOWN_FORHEART_THREAD = setInterval(() => {
            if(second > 0) {
                second --;
            }if (second === 0 && min > 0) {
                second = 59;
                min --;
            }else if (second === 0 && min === 0){
                this.REGETHEART = getHeart;
                clearInterval(this.COUNTDOWN_FORHEART_THREAD)
                this.COUNTDOWN_FORHEART_THREAD = null;
                //展示继续挑战页面
                this.showContinuePage();
                return 
            }
            let showStr =('0'+min).substr(-2) + ':' + ('0'+second).substr(-2);
            countDown.text = showStr;
        }, 1000)

        this.CURRENT_LOSE_TIME ++ ;
    }

    private showContinuePage() {
        try {
            platform.request({
                url:platform.globalPath + '/user/waitStar',
                method: 'POST',
                data: {userId: wx.getStorageSync('userId')}
            })
        } catch (error) {
            
        }
        let leftLabel:any = this.failDialog.getChildByName('leftLabel');
        let shareBtn: any = this.failDialog.getChildByName('shareBtn');
        leftLabel.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.leftLabelBtn, this);
        shareBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.shareApp, this);
        this.removeChild(this.failDialog)

        let continuePage: any = new eui.Component();
        continuePage.skinName = 'getHeart';
        continuePage.getChildByName('heartNum').text = `获得${this.REGETHEART}颗小心心`;
        continuePage.y = this.myOption.stageHeight / 2 - continuePage.height / 2 - 100;
        this.addChild(continuePage);

        let continueBtn = continuePage.getChildByName('continueBtn');
        continueBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, () => {
            this.removeChild(this.myMask);
            this.removeChild(continuePage);
            this.initCountDown();
            this.addEventListener(egret.Event.ENTER_FRAME, this.loop, this);
            this.showPop();
            while(this.REGETHEART > 0) {
                this.REGETHEART --;
                this.addHeart();
            }
        }, this);
    }

    /**
     * 展示阴影遮罩层
     */
    private initMask() {
        this.myMask = new eui.Rect();
        this.myMask.width = this.myOption.stageWidth;
        this.myMask.height = this.myOption.stageHeight;
        this.myMask.fillColor = 0x000000;
        this.myMask.fillAlpha = 0.7
    }

    private createBoomAnimation(x, y, color) {
        var boom = this.createBitmapByName(`${color}_boom_png`);
        boom.x = x;
        boom.y = y;
        boom.scaleX = 0;
        boom.scaleY = 0;
        this.BOOM_PANEL.addChild(boom);

        egret.Tween
            .get(boom, {
                loop: false,//设置循环播放
                onChangeObj: this//更新函数作用域
            })
            .to({scaleX: 1,scaleY: 1,x:x - 95, y: y - 95}, 200)//设置2000毫秒内 rotation 属性变为360
            // .to( {alpha:0}, 100 )
            .call(() => {}, this);
    }

    private rnd(start, end){
        return Math.floor(Math.random() * (end - start) + start)
    }

    public isCollideWith(origin, target) {
        let spX = origin.x + origin.width / 2;
        let spY = origin.y + origin.height / 2 + this.GAMEFOOTER_Y;
        return !!(   spX >= target.x
                && spX <= target.x + target.width
                && spY >= target.y
                && spY <= target.y + target.height  )
    }

    private getRandomColor() {
        return this.BALLOON_COLOR_LIST[Math.floor(Math.random() * Math.floor(this.BALLOON_COLOR_LIST.length))];
    }

    /**
	  * 获取每关基础数据
	  */
	private getLevelBaseData() {
		let levelTargetBalloonNum;
        let levelBalloonSpeed;
        let countDownTime;
		if(this.CURRENT_LEVEL <= 5) {
            levelTargetBalloonNum = Math.floor(Math.random() * 3 + 1);
            levelBalloonSpeed = 3;
            countDownTime = 40;
        }else if(this.CURRENT_LEVEL > 5 && this.CURRENT_LEVEL <= 15) {
            levelTargetBalloonNum = Math.floor(Math.random() * 5 + 3);
            levelBalloonSpeed = 6;
            countDownTime = 30;
        }else if(this.CURRENT_LEVEL > 15 && this.CURRENT_LEVEL <= 25) {
            levelTargetBalloonNum = Math.floor(Math.random() * 6 + 5);
            levelBalloonSpeed = 9;
            countDownTime = 20;
        }else {
            levelTargetBalloonNum = Math.floor(Math.random() * 6 + 5);
            levelBalloonSpeed = 12;
            countDownTime = 10;
        }

        return {
            levelTargetBalloonNum,
            levelBalloonSpeed,
            countDownTime
        }
	 }

     /**
      * 移除当前的内容
      */
     private release() {
         this.removeChildren();
     }
}